package com.szosen.jkzj.activity.mbgy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Response;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableLayout;

import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;
import com.szosen.database.DBService;
import com.szosen.database.MedicineDesc;
import com.szosen.database.UploadRecord;
import com.szosen.database.Visit_info2;
import com.szosen.database.base_info;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.json.JsonUtil;
import com.szosen.json.Root_Return;
import com.szosen.json.Visit;
import com.szosen.json.DiabetesMedicines;
import com.szosen.json.DiabetesVisit;
import com.szosen.json.HypertensionMedicines;
import com.szosen.util.BackGroundThread;
import com.szosen.util.FileSaveUtil;
import com.szosen.util.JktjBitmapUtil;
import com.szosen.util.SharedpreferenceUtil;
import com.szosen.util.StringUtils;
import com.szosen.util.TimeHelper;
import com.szosen.util.ToastTool;
import com.szosen.util.VisitContants;
import com.szosen.web.Fetch;
import com.szosen.web.ResultListener;
import com.szosen.web.WebService;
import com.szosen.xml.XmlTool;

public class GlycuresisTure extends BaseActivity {

	private boolean lock = false;
	private Button editHelpBtn;
	private Button saveBtn;
	private View bodySv;
	private String saveTemp;
	private String time;
	EditText otherMedicineDesc1_et;
	EditText medicineFrequency1_et;
	EditText medicineDosage1_et;
	EditText otherMedicineDesc2_et;
	EditText medicineFrequency2_et;
	EditText medicineDosage2_et;
	EditText otherMedicineDesc3_et;
	EditText medicineFrequency3_et;
	EditText medicineDosage3_et;
	EditText otherMedicineDesc4_et;
	EditText medicineFrequency4_et;
	EditText medicineDosage4_et;
	String from = "";
	ImageView iv_mainImage;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.glycuresis_report);
		super.setTitleContent("【糖尿病】");
		initView();
		from = getIntent().getStringExtra("flag");
		if (TextUtils.isEmpty(from)) {
			from = "";
		}
		Button glycuresis_btn_save = (Button) findViewById(R.id.glycuresis_btn_save);
		glycuresis_btn_save.setVisibility(View.GONE);
		Button gxy_tack_photo = (Button) findViewById(R.id.gxy_tack_photo);
		gxy_tack_photo.setVisibility(View.GONE);

	}

	private void initYYQK() {
		Activity tl = this;
		// <otherMedicineDesc>药物名称</otherMedicineDesc>
		// <medicineFrequency>次数</medicineFrequency>
		// <days>天数</days>
		// <medicineDosage>每次剂量</medicineDosage>
		// <medicineUnit>剂量单位</medicineUnit>
		otherMedicineDesc1_et = (EditText) tl.findViewById(R.id.yyqk_DrugName1);
		medicineFrequency1_et = (EditText) tl.findViewById(R.id.yyqk_Usage1);
		medicineDosage1_et = (EditText) tl.findViewById(R.id.yyqk_Consumption1);
		otherMedicineDesc2_et = (EditText) tl.findViewById(R.id.yyqk_DrugName2);
		medicineFrequency2_et = (EditText) tl.findViewById(R.id.yyqk_Usage2);
		medicineDosage2_et = (EditText) tl.findViewById(R.id.yyqk_Consumption2);
		otherMedicineDesc3_et = (EditText) tl.findViewById(R.id.yyqk_DrugName3);
		medicineFrequency3_et = (EditText) tl.findViewById(R.id.yyqk_Usage3);
		medicineDosage3_et = (EditText) tl.findViewById(R.id.yyqk_Consumption3);
		otherMedicineDesc4_et = (EditText) tl
				.findViewById(R.id.yyqk_DrugNameOther);
		medicineFrequency4_et = (EditText) tl
				.findViewById(R.id.yyqk_UsageOther);
		medicineDosage4_et = (EditText) tl
				.findViewById(R.id.yyqk_ConsumptionOther);
		String datas = SharedpreferenceUtil.getYaowuDatas(tl, "",
				SharedpreferenceUtil.YAOWUDATAS_TNB);
		// String[] yaowus = datas.trim().split(
		// SharedpreferenceUtil.YAOWUDATAS_SPLIT);
		String[] yaowus = VisitContants.TNB.items;
		setChoiceEditText(R.id.yyqk_DrugName1, yaowus, null);
		setChoiceEditText(R.id.yyqk_DrugName2, yaowus, null);
		setChoiceEditText(R.id.yyqk_DrugName3, yaowus, null);
		setChoiceEditText(R.id.yyqk_DrugNameOther, yaowus, null);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	// 拍照后相片的Uri
	private Uri imageUri;
	// 拍照后相片path
	private String imagePath;

	public void tackPhoto(View view) {
		/**
		 * 创建File对象，用于存储拍照后的图片 调用getExternalCacheDir方法可以得到应用关联目录
		 * /sdcard/Android/data/<package name>/cache 为何调用getExternalCacheDir？
		 * 因为Android从6.0开始。读写SD卡被认为是危险权限。如果将图片放在其他目录，需要动态申请权限 而使用关联目录可以跳过这一步
		 * */
		String userPath = FileSaveUtil.getSDCardPath()
				+ BaseActivity.getArchiveBean().getName();
		File temp = new File(userPath);
		if (!temp.exists()) {
			temp.mkdir();
		}
		if (TextUtils.isEmpty(imagePath)) {
			imagePath = userPath + "/" + time + ".jpg";
		}
		File outputImage = new File(imagePath);
		try {
			if (outputImage.exists())
				outputImage.delete();
			outputImage.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (Build.VERSION.SDK_INT >= 24) {
			/**
			 * 从Android7.0开始，直接使用本地的真是路径的URI被认为是不安全的，会抛出FileUriExposeException
			 * 而FileProvider是一种特殊的ContentProvider，可以给外部选择性的分享Uri，提高安全性
			 */
			imageUri = FileProvider.getUriForFile(GlycuresisTure.this,
					"com.example.testing.picturetest", outputImage);
		} else {
			imageUri = Uri.fromFile(outputImage);
		}
		// 启动相机
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		intent.putExtra("android.intent.extra.quickCapture", true);
		startActivityForResult(intent, TAKE_PHOTO);
	}

	private static final int TAKE_PHOTO = 1;
	private static final int CHOOSE_PHOTO = 2;
	private static final int APPLY_PERMISSION = 3;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case TAKE_PHOTO:
			if (resultCode == RESULT_OK) {
				try {
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inPreferredConfig = Config.RGB_565;
					Bitmap bitmap = BitmapFactory.decodeStream(
							getContentResolver().openInputStream(imageUri),
							null, options);
					// 某些手机拍完照之后会自动旋转照片，以下代码把图片还原为旋转前状态
					int degree = PhotoRotateUtil.getBitmapDegree(imagePath);
					bitmap = PhotoRotateUtil.rotateBitmapByDegree(bitmap,
							degree);
					iv_mainImage.setImageBitmap(bitmap);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;
		}
	}

	private void upload() {
		Visit_info2 uploadBean = getUpload();
		if (uploadBean == null) {
			return;
		}
		// 这里将高血压的bean类转化为需要的json数据。
		final Visit data = new Visit();
		// 随访标识
		data.setVisitId("");
		// 档案编码
		data.setPhrId("");
		// empiid
		data.setEmpiId("");
		data.setIdCard(uploadBean.getIdCard());
		data.setVisitDate(uploadBean.getVisitDate());
		// data.setVisitDoctor(hypertension_edt_turedoctor.getText().toString());//
		// 随访医生
		// data.setVisitUser(hypertension_edt_turedoctor.getText().toString());//
		// 随访医生
		data.setVisitUnit("");// 随访机构。
		data.setVisitWay(uploadBean.getVisitType());
		data.setNextDate(uploadBean.getNextDate());// 下次随访日期
		// data.setVisitEffect(uploadBean.getVisitEffect());//转归
		// data.setNoVisitReason(uploadBean.getNoVisitReason());//失访原因
		data.setDiabetesType("");// 暂时没实现 病例种类
		data.setDiabetesChange("");// 发生转型
		data.setConstriction(StringUtils.parseIntByStr(uploadBean
				.getConstriction()));// 收缩压
		data.setDiastolic(StringUtils.parseIntByStr(uploadBean.getDiastolic()));
		data.setWeight(StringUtils.parseDoubleByStr(uploadBean.getWeight()));
		data.setTargetWeight(StringUtils.parseDoubleByStr(uploadBean
				.getTargetWeight()));
		data.setBmi(StringUtils.parseDoubleByStr(uploadBean.getBmi()));
		// data.setTargetBmi(uploadBean.getBmi());//目标的bmi、暂时没实现
		data.setOtherSigns(uploadBean.getOtherSigns());
		data.setDiet(uploadBean.getDiet());

		data.setSmokeCount(StringUtils.parseIntByStr(uploadBean.getSmokeCount()));
		data.setTargetSmokeCount(StringUtils.parseIntByStr(uploadBean
				.getTargetSmokeCount()));
		data.setTrainTimesWeek(StringUtils.parseIntByStr(uploadBean
				.getTrainTimesWeek()));
		data.setTargetTrainTimesWeek(StringUtils.parseIntByStr(uploadBean
				.getTargetTrainTimesWeek()));
		data.setTrainMinute(StringUtils.parseIntByStr(uploadBean
				.getTrainMinute()));
		data.setTargetTrainMinute(StringUtils.parseIntByStr(uploadBean
				.getTargetTrainMinute()));
		data.setPsychologyChange(uploadBean.getPsychologyChange());
		data.setObeyDoctor(uploadBean.getObeyDoctor());
		// data.setLastModifyUser(lastModifyUser);// 最后修改人
		// data.setLastModifyUnit(lastModifyUnit);// 最后修改单位
		// data.setLastModifyDate(lastModifyUser);// 最后修改日期

		// data.setManaUnitId(manaUnitId);//管辖机构
		// data.setManaDoctorId(manaDoctorId);//责任医生
		DiabetesVisit dv = new DiabetesVisit();
		dv.setPulsation(uploadBean.getPulsation());
		String ss = uploadBean.getSymptoms();
		if (!TextUtils.isEmpty(ss) && ss.endsWith(",")) {
			ss = ss.substring(0, ss.length() - 1);
		}
		dv.setSymptoms(ss);
		dv.setOtherSymptoms(uploadBean.getOtherSymptoms());
		dv.setComplicationChange(uploadBean.getComplicationChange());
		dv.setAdverseReactions(uploadBean.getAdverseReactions());
		dv.setMedicine(uploadBean.getMedicine());
		dv.setTc(StringUtils.parseDoubleByStr(uploadBean.getTc()));
		dv.setHdl(StringUtils.parseDoubleByStr(uploadBean.getHdl()));
		dv.setLdl(StringUtils.parseDoubleByStr(uploadBean.getLdl()));
		dv.setFood(StringUtils.parseIntByStr(uploadBean.getFood()));
		dv.setTargetFood(StringUtils.parseIntByStr(uploadBean.getTargetFood()));
		dv.setFbs(StringUtils.parseDoubleByStr(uploadBean.getFbs()));
		dv.setPbs(StringUtils.parseDoubleByStr(uploadBean.getPbs()));
		dv.setUnit(uploadBean.getUnit());
		dv.setHbA1c(uploadBean.getHbA1c());
		dv.setBloodFat(uploadBean.getBloodFat());
		dv.setGlycopenia(uploadBean.getGlycopenia());
		dv.setTestDate(uploadBean.getTestDate());
		// dv.setCbyx(cbyx);//初步印象
		dv.setReferralReason(uploadBean.getAdverseReactions());// 转诊原因
		// dv.setZljg("");//治疗经过
		// dv.setZzys(zzys);//转诊医生
		// dv.setLxdh(lxdh)(zzys);//联系电话
		// dv.setZzjg(zzjg)(zzys);//转诊机构
		// dv.setZzsj(zzsj)(zzys);//转诊时间
		// dv.setAgencyAndDept(agencyAndDept)(zzys);//接诊机构及科室
		// dv.setJzks(jzks)(zzys);//接诊科室
		// dv.setJzys(jzys)(zzys);//接诊医生

		List<MedicineDesc> descs = uploadBean.getMedicineDescs();
		List<DiabetesMedicines> dms = new ArrayList<DiabetesMedicines>();
		if (descs != null && descs.size() > 0) {
			for (int i = 0; i < descs.size(); i++) {
				MedicineDesc desc = descs.get(i);
				DiabetesMedicines dm = new DiabetesMedicines();
				dm.setMedicineName(desc.getOtherMedicineDesc());// 名称
				dm.setMedicineId(VisitContants.getTNBCodeByYaowuName(desc
						.getOtherMedicineDesc()));// id
				dm.setMedicineFrequency(StringUtils.parseIntByStr(desc
						.getMedicineFrequency()));// 次数
				dm.setDays(StringUtils.parseIntByStr(desc.getDays()));// 天数
				dm.setMedicineDosage(StringUtils.parseDoubleByStr(desc
						.getMedicineDosage()));// 每次剂量
				dm.setMedicineUnit("mg");// 计量单位
				// hm.setCreateDate(createDate);//开药时间默认当天
				// hm.setMedicineTotalDosage(medicineTotalDosage);//总剂量
				// hm.setOtherMedicineDesc();//其他用药描述
				dms.add(dm);
			}
		}
		dv.setDiabetesMedicines(dms);
		// data.setHypertensionVisit(hv);// 高血压随访
		data.setDiabetesVisit(dv);// 糖尿病随访
		// 完成一个json的上传数据填充

		String uploadStr = XmlTool.TNB2String(uploadBean);
		boolean b = DBService.add(uploadBean);
		final String uploadTime = uploadBean.getTime();
		data.setAppvisitId(uploadTime);
		WebService.uploadPicVisit(context, uploadBean.getImagePath(),
				new StringCallback() {

					@Override
					public void onSuccess(String str, Call call,
							Response response) {
						// 查看
						String fileId = "";
						try {
							JSONObject strJsonObject = new JSONObject(str);
							JSONArray dataArray = strJsonObject
									.optJSONArray("data");
							if (dataArray != null && dataArray.length() > 0) {
								JSONObject data0;
								data0 = (JSONObject) dataArray.get(0);
								fileId = data0.optString("fileId");
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						System.out.println("返回的图片的信息：" + str);
						if (!TextUtils.isEmpty(fileId)) {
							data.setPhoto(fileId);
						}
						WebService.addVisit(context, uploadTime, jsonHandler,
								data, UploadRecord.Type.TNB);
					}

					@Override
					public void onError(Call call, Response response,
							Exception e) {
						super.onError(call, response, e);
						WebService.addVisit(context, uploadTime, jsonHandler,
								data, UploadRecord.Type.TNB);
					}

					@Override
					public void onBefore(BaseRequest request) {
						super.onBefore(request);
						System.out.println("执行了请求前");
					}

					@Override
					public void onAfter(String t, Exception e) {
						super.onAfter(t, e);
						System.out.println("执行了请求后");
					}
				});
		// WebService.addVisit(context, uploadTime, jsonHandler, data,
		// UploadRecord.Type.TNB);
	}

	private static final int what_success_ok = 65;
	private static final int what_failed = 77;
	private static final int what_error = 87;
	Handler jsonHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case what_success_ok:
				ToastTool.showLong(context, "上传成功");
				break;
			case what_failed:
				ToastTool.showLong(context, "上传错误");
				break;
			case what_error:
				ToastTool.showLong(context, "访问出错，请检查网络或配置信息");
				break;
			}
		};
	};

	protected void initView() {
		initYYQK();
		setChoiceEditText();
		iv_mainImage = (ImageView) findViewById(R.id.glycuresis_iv_mainImage);
		editHelpBtn = (Button) findViewById(R.id.glycuresis_edit_helpbutton);
		saveBtn = (Button) findViewById(R.id.glycuresis_btn_save);
		saveBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				upload();
			}

		});
		bodySv = findViewById(R.id.glycuresis_body);
		final EditText glycuresis_edt_bloodpresure = (EditText) findViewById(R.id.glycuresis_edt_bloodpresure);
		glycuresis_edt_bloodpresure
				.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								context);
						LayoutInflater inflater = (LayoutInflater) context
								.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						TableLayout tl = (TableLayout) inflater.inflate(
								R.layout.health_check_bloodpre, null);
						final EditText shuzhang = (EditText) tl
								.findViewById(R.id.et_shuzhang);
						final EditText shousuo = (EditText) tl
								.findViewById(R.id.et_shousuo);
						builder.setView(tl);
						builder.setTitle("填写您的血压");
						builder.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										glycuresis_edt_bloodpresure
												.setText(shousuo.getText()
														+ "/"
														+ shuzhang.getText());
									}
								});
						builder.setNegativeButton("取消", null);
						builder.create().show();
					}
				});
		final EditText glycuresis_druglist = (EditText) findViewById(R.id.glycuresis_druglist);
		glycuresis_druglist.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ShowDialog.show(GlycuresisTure.this, glycuresis_druglist,
						ShowDialog.TYPE_GLY);
			}
		});

	}

	@Override
	@SuppressLint("ResourceAsColor")
	@SuppressWarnings("unchecked")
	protected void onResume() {
		super.onResume();
		setText(R.id.glycuresis_patientname, BaseActivity.getName());
		time = getIntent().getStringExtra("time");
		if (TextUtils.isEmpty(time)) {
			if ("new".equals(from)) {
				// 如果是新的记录。就从健康体检数据库获取最新的测量结果。
				base_info b = new base_info();
				b.setIdCard(BaseActivity.getIdCard());
				List<base_info> bs = (List<base_info>) DBService
						.queryByIdCard(b);
				if (bs != null && bs.size() > 0) {
					base_info bean = bs.get(bs.size() - 1);
					bean.getHeight();
					// 体重
					setText(R.id.glycuresis_edt_weight, bean.getWeight());
					setText(R.id.glycuresis_edt_index, bean.getBmi());
					setText(R.id.glycuresis_edt_bloodpresure,
							bean.getConstriction_L() + "/"
									+ bean.getDiastolic_L());
				}
				if ("new".equals(from)) {
					setText(R.id.glycuresis_reportdate,
							TimeHelper.getJKTJCheckDate());
				}
			}
			return;
		} else {
			Visit_info2 queryBean = new Visit_info2();
			queryBean.setTime(time);
			List<Object> lists = (List<Object>) DBService.queryByKey(queryBean);
			if (lists.size() > 0) {
				Visit_info2 visit_info = (Visit_info2) lists.get(0);
				setData2UI(visit_info);
			}
		}
	}

	public void printTable(View view) {
		Visit_info2 visit_info = getUpload();
		if (visit_info != null) {
			final List<Visit_info2> lists = new ArrayList<Visit_info2>();
			lists.add(visit_info);
			new BackGroundThread(new BackGroundThread.BackGroundTask() {
				@Override
				public void process() {
					JktjBitmapUtil.createTNBBitmap(context, lists);
				}
			}).start();
		} else {
			ToastTool.showShort(context, "打印错误，请检查填空！");
		}
	}

	/***
	 * 检查编辑框。是否可以编辑的。
	 * 
	 * @return
	 */
	public boolean isEditTextOK() {
		if (TextUtils.isEmpty(getTextById(R.id.glycuresis_turemethod))) {
			ToastTool.showShort(context, "随访方式不能为空！");
			return false;
		} else if (TextUtils
				.isEmpty(getTextById(R.id.glycuresis_det_nextturedate))) {
			ToastTool.showShort(context, "下次随访日期不能为空！");
			return false;
		} else if (TextUtils.isEmpty(getTextById(R.id.glycuresis_reportdate))) {
			ToastTool.showShort(context, "随访日期不能为空!");
			return false;
		} else if (TextUtils
				.isEmpty(getTextById(R.id.glycuresis_edt_bloodpresure))
				|| getTextById(R.id.glycuresis_edt_bloodpresure).equals("/")) {
			ToastTool.showShort(context, "血压不能为空!");
			return false;
		} else if (TextUtils.isEmpty(getTextById(R.id.glycuresis_edt_smoking))) {
			ToastTool.showShort(context, "日吸烟量不能为空!");
			return false;
		} else if (TextUtils.isEmpty(getTextById(R.id.glycuresis_edt_drinking))) {
			ToastTool.showShort(context, "日饮酒量不能为空!");
			return false;
		} else if (TextUtils
				.isEmpty(getTextById(R.id.glycuresis_edt_drinkingtype))) {
			ToastTool.showShort(context, "饮酒种类不能为空!");
			return false;
		} else if (TextUtils.isEmpty(getTextById(R.id.glycuresis_edt_sport1))) {
			ToastTool.showShort(context, "运动次数不能为空!");
			return false;
		} else if (TextUtils
				.isEmpty(getTextById(R.id.glycuresis_sce_medicalobey))) {
			ToastTool.showShort(context, "服药依从性不能为空!");
			return false;
		}
		return true;
	}

	public Visit_info2 getUpload() {
		if (!isEditTextOK()) {
			return null;
		}
		final Visit_info2 uploadBean = new Visit_info2();
		uploadBean.setIdCard(BaseActivity.getIdCard());
		uploadBean.setVisitDate(getTextById(R.id.glycuresis_reportdate));
		String visitWay = getTextById(R.id.glycuresis_turemethod);
		if (TextUtils.isEmpty(time)) {
			time = TimeHelper.getMainTimeKey();
		}
		if (!TextUtils.isEmpty(imagePath)) {
			uploadBean.setImagePath(imagePath);
		}
		uploadBean.setTime(time);
		uploadBean.setCheckid(time);
		if ("门诊".equals(visitWay)) {
			visitWay = "1";
		} else if ("家庭".equals(visitWay)) {
			visitWay = "2";
		} else if ("电话".equals(visitWay)) {
			visitWay = "3";
		} else if ("短信".equals(visitWay)) {
			visitWay = "4";
		} else if ("网络".equals(visitWay)) {
			visitWay = "5";
		} else if ("其他".equals(visitWay)) {
			visitWay = "9";
		}
		uploadBean.setVisitWay(visitWay);
		// 下次随访日期
		uploadBean.setNextDate(getTextById(R.id.glycuresis_det_nextturedate));
		String symptoms = getTextById(R.id.glycuresis_symps);
		StringBuilder sb_symptoms = new StringBuilder();
		String[] symStrings = symptoms.split("\t");
		for (int i = 0; i < symStrings.length; i++) {
			if (symStrings[i].contains("无症状")) {
				sb_symptoms.append("8,");
			}
			if (symStrings[i].contains("多饮")) {
				sb_symptoms.append("1,");
			}
			if (symStrings[i].contains("多食")) {
				sb_symptoms.append("2,");
			}
			if (symStrings[i].contains("多尿")) {
				sb_symptoms.append("3,");
			}
			if (symStrings[i].contains("视力模糊")) {
				sb_symptoms.append("4,");
			}
			if (symStrings[i].contains("感染")) {
				sb_symptoms.append("5,");
			}
			if (symStrings[i].contains("手脚麻木")) {
				sb_symptoms.append("6,");
			}
			if (symStrings[i].contains("下肢浮肿")) {
				sb_symptoms.append("7,");
			}
			if (symStrings[i].contains("体重明显下降")) {
				// sb_symptoms.append("9,");
			} else if (symStrings[i].contains("其他")) {
				// sb_symptoms.append();
				sb_symptoms.append("9,");
				String qita = symptoms.substring(symptoms.indexOf("其他"));
				if (!TextUtils.isEmpty(qita)) {
					uploadBean.setOtherSymptoms(qita.replace("其他", "")
							.replace("(", "").replace(")", ""));
				}
			}
		}

		uploadBean.setSymptoms(sb_symptoms.toString());
		String gh = getTextById(R.id.glycuresis_edt_bloodpresure);
		String[] ghs = gh.split("/");
		if (ghs.length >= 2) {
			uploadBean.setDiastolic(ghs[1]);
			uploadBean.setConstriction(ghs[0]);
		}
		uploadBean.setWeight(getTextById(R.id.glycuresis_edt_weight));
		uploadBean
				.setTargetWeight(getTextById(R.id.glycuresis_edt_weighttarget));
		uploadBean.setBmi(getTextById(R.id.glycuresis_edt_index));
		uploadBean.setBmi(getTextById(R.id.glycuresis_edt_index));
		uploadBean.setOtherSigns(getTextById(R.id.glycuresis_edt_signother));
		String zubei = getTextById(R.id.glycuresis_edt_zubei);
		if ("触及".equals(zubei)) {
			uploadBean.setPulsation("2");
		} else if ("未触及".equals(zubei)) {
			uploadBean.setPulsation("1");
		}
		uploadBean.setSmokeCount(getTextById(R.id.glycuresis_edt_smoking));
		uploadBean
				.setTargetSmokeCount(getTextById(R.id.glycuresis_edt_smokingtarget));
		String yinjiu = getTextById(R.id.glycuresis_edt_drinkingtype);
		String[] yinjius = yinjiu.split("\t");
		StringBuilder sb_yinjiu = new StringBuilder();
		for (int j = 0; j < yinjius.length; j++) {
			switch (yinjius[j]) {
			case "白酒(≥42度)":
				sb_yinjiu.append("1,");
				break;
			case "白酒(＜42度)":
				sb_yinjiu.append("2,");
				break;
			case "啤酒":
				sb_yinjiu.append("3,");
				break;
			case "黄酒、米酒":
				sb_yinjiu.append("4,");
				break;
			case "葡萄酒":
				sb_yinjiu.append("5,");
				break;
			case "其他":
				sb_yinjiu.append("9,");
				break;
			case "不饮酒":
				sb_yinjiu.append("10,");
				break;

			default:
				break;
			}
		}
		uploadBean.setDrinkTypeCode(sb_yinjiu.toString());
		uploadBean.setDrinkCount(getTextById(R.id.glycuresis_edt_drinking));
		uploadBean
				.setTargetDrinkCount(getTextById(R.id.glycuresis_edt_drinkingtarget));
		uploadBean.setTrainTimesWeek(getTextById(R.id.glycuresis_edt_sport1));
		uploadBean
				.setTargetTrainTimesWeek(getTextById(R.id.glycuresis_edt_sport1target));
		uploadBean.setTrainMinute(getTextById(R.id.glycuresis_edt_sport2));
		uploadBean
				.setTargetTrainMinute(getTextById(R.id.glycuresis_edt_sport2target));
		String loseWeight = getTextById(R.id.glycuresis_et_needjianqingweight);
		if (loseWeight.equals("不需要")) {
			loseWeight = "1";
		} else if (loseWeight.equals("需要")) {
			loseWeight = "2";
		}
		uploadBean.setLoseWeight(loseWeight);
		uploadBean.setFood(getTextById(R.id.glycuresis_et_food));
		uploadBean.setTargetFood(getTextById(R.id.edt_foodtarget));
		uploadBean.setFbs(getTextById(R.id.glycuresis_edt_sugar));
		uploadBean.setPbs(getTextById(R.id.glycuresis_edt_sugarcanhou));
		String xinli = getTextById(R.id.glycuresis_sce_mentaladjust);
		switch (xinli) {
		case "良好":
			xinli = "1";
			break;
		case "一般":
			xinli = "2";
			break;
		case "差":
			xinli = "3";
			break;
		default:
			break;
		}
		uploadBean.setPsychologyChange(xinli);
		String zhunyi = getTextById(R.id.glycuresis_sce_obey);
		switch (zhunyi) {
		case "良好":
			zhunyi = "1";
			break;
		case "一般":
			zhunyi = "2";
			break;
		case "差":
			zhunyi = "3";
			break;
		default:
			break;
		}
		uploadBean.setObeyDoctor(zhunyi);
		uploadBean.setTc(getTextById(R.id.glycuresis_edt_TC));
		uploadBean.setHdl(getTextById(R.id.glycuresis_edt_HDL));
		uploadBean.setLdl(getTextById(R.id.glycuresis_et_LDL));
		uploadBean.setHbA1c(getTextById(R.id.glycuresis_edt_hemoglobin));
		uploadBean.setTestDate(getTextById(R.id.glycuresis_edt_examinedate));
		String fuyao = getTextById(R.id.glycuresis_sce_medicalobey);
		switch (fuyao) {
		case "规律":
			fuyao = "1";
			break;
		case "间断":
			fuyao = "2";
			break;
		case "不服药":
			fuyao = "3";
			break;
		case "拒绝服药":
			fuyao = "4";
			break;
		default:
			break;
		}
		uploadBean.setMedicine(fuyao);
		// 药物不良反应
		String ywblfy = getTextById(R.id.glycuresis_scedt_drugreaction);
		switch (ywblfy) {
		case "无":
			ywblfy = "1";
			break;
		case "有":
			ywblfy = "2";
			break;
		default:
			break;
		}
		uploadBean.setAdverseReactions(ywblfy);
		// 低血糖反应
		String dxtfy = getTextById(R.id.glycuresis_sce_rhg);
		switch (dxtfy) {
		case "无":
			dxtfy = "1";
			break;
		case "偶尔":
			dxtfy = "2";
			break;
		case "频繁":
			dxtfy = "3";
			break;
		default:
			break;
		}
		uploadBean.setGlycopenia(dxtfy);
		// 随访分类
		String sffl = getTextById(R.id.glycuresis_sce_tureclass);
		switch (sffl) {
		case "控制满意":
			sffl = "1";
			break;
		case "控制不满意":
			sffl = "2";
			break;
		case "不良反应":
			sffl = "3";
			break;
		case "并发症":
			sffl = "4";
			break;
		default:
			break;
		}
		uploadBean.setVisitType(sffl);
		String jigou = getTextById(R.id.glycuresis_referral_Organization);
		uploadBean.setReferralOffice(jigou);
		// 并发症变化
		// String bfzbh = getTextById(R.id.glycuresis_edt_bingfazheng);
		String bfzbh = getTextById(R.id.glycuresis_edt_bingfazheng);
		switch (bfzbh) {
		case "有新并发症":
			bfzbh = "1";
			break;
		case "原有并发症加重":
			bfzbh = "2";
			break;
		default:
			break;
		}
		List<MedicineDesc> lists = new ArrayList<MedicineDesc>();
		MedicineDesc oneBean = null;
		if (!TextUtils.isEmpty(otherMedicineDesc1_et.getText().toString())) {
			oneBean = new MedicineDesc();
			oneBean.setOtherMedicineDesc(otherMedicineDesc1_et.getText()
					.toString());
			oneBean.setMedicineFrequency(medicineFrequency1_et.getText()
					.toString());
			oneBean.setMedicineDosage(medicineDosage1_et.getText().toString());
			oneBean.setDays("1");
			lists.add(oneBean);
		}
		if (!TextUtils.isEmpty(otherMedicineDesc2_et.getText().toString())) {
			oneBean = new MedicineDesc();
			oneBean.setOtherMedicineDesc(otherMedicineDesc2_et.getText()
					.toString());
			oneBean.setMedicineFrequency(medicineFrequency2_et.getText()
					.toString());
			oneBean.setMedicineDosage(medicineDosage2_et.getText().toString());
			oneBean.setDays("1");
			lists.add(oneBean);
		}
		if (!TextUtils.isEmpty(otherMedicineDesc3_et.getText().toString())) {
			oneBean = new MedicineDesc();
			oneBean.setOtherMedicineDesc(otherMedicineDesc3_et.getText()
					.toString());
			oneBean.setMedicineFrequency(medicineFrequency3_et.getText()
					.toString());
			oneBean.setMedicineDosage(medicineDosage3_et.getText().toString());
			oneBean.setDays("1");
			lists.add(oneBean);
		}
		if (!TextUtils.isEmpty(otherMedicineDesc4_et.getText().toString())) {
			oneBean = new MedicineDesc();
			oneBean.setOtherMedicineDesc(otherMedicineDesc4_et.getText()
					.toString());
			oneBean.setMedicineFrequency(medicineFrequency4_et.getText()
					.toString());
			oneBean.setMedicineDosage(medicineDosage4_et.getText().toString());
			oneBean.setDays("1");
			lists.add(oneBean);
		}
		uploadBean.setXml(XmlTool.getMedicineDescsXml(lists));
		uploadBean.setMedicineDescs(lists);
		uploadBean.setComplicationChange(bfzbh);
		// 转诊原因
		uploadBean
				.setReferralReason(getTextById(R.id.glycuresis_referral_reason));
		// uploadBean.setNextDate(nextDate);//下次随访日期
		// 添加到数据库
		return uploadBean;
	}

	private void setData2UI(Visit_info2 uploadBean) {
		setText(R.id.glycuresis_reportdate, uploadBean.getVisitDate());
		setText(R.id.glycuresis_turenum, uploadBean.getTime());
		// (nextDate);//下次随访日期
		setText(R.id.glycuresis_det_nextturedate, uploadBean.getNextDate());
		String visitWay = uploadBean.getVisitWay();
		if ("1".equals(visitWay)) {
			visitWay = "门诊";
		} else if ("2".equals(visitWay)) {
			visitWay = "家庭";
		} else if ("3".equals(visitWay)) {
			visitWay = "电话";
		} else if ("4".equals(visitWay)) {
			visitWay = "短信";
		} else if ("5".equals(visitWay)) {
			visitWay = "网络";
		} else if ("9".equals(visitWay)) {
			visitWay = "其他";
		}
		String temp = uploadBean.getImagePath();
		if (!TextUtils.isEmpty(temp)) {
			imagePath = temp;
		}
		if (!TextUtils.isEmpty(imagePath)) {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Config.RGB_565;
			Bitmap imageBitmap = BitmapFactory.decodeFile(imagePath, options);
			if (imageBitmap != null) {
				iv_mainImage.setImageBitmap(imageBitmap);
			}
		}
		//转归
				String visitEffect = uploadBean.getVisitEffect();
				if ("1".equals(visitEffect)) {
					visitEffect = "继续随访";
				} else if ("2".equals(visitEffect)) {
					visitEffect = "暂时失访";
				} else if ("3".equals(visitEffect)) {
					visitEffect = "终止管理";
				}
				setText(R.id.hypertension_zhuangui, visitEffect);
		setText(R.id.glycuresis_turemethod, visitWay);
		// 症状
		String symptoms = uploadBean.getSymptoms();
		StringBuilder sb_symptoms = new StringBuilder();
		String[] symStrings = symptoms.split("\t");
		for (int i = 0; i < symStrings.length; i++) {
			if (symStrings[i].contains("8")) {
				sb_symptoms.append("无症状\t");
			}
			if (symStrings[i].contains("1")) {
				sb_symptoms.append("多饮\t");
			}
			if (symStrings[i].contains("2")) {
				sb_symptoms.append("多食\t");
			}
			if (symStrings[i].contains("3")) {
				sb_symptoms.append("多尿\t");
			}
			if (symStrings[i].contains("4")) {
				sb_symptoms.append("视力模糊\t");
			}
			if (symStrings[i].contains("5")) {
				sb_symptoms.append("感染\t");
			}
			if (symStrings[i].contains("6")) {
				sb_symptoms.append("手脚麻木\t");
			}
			if (symStrings[i].contains("7")) {
				sb_symptoms.append("下肢浮肿\t");
			}
			if (symStrings[i].contains("体重明显下降")) {
				// sb_symptoms.append("9,");
			} else if (symStrings[i].contains("9")) {
				// sb_symptoms.append();
				sb_symptoms.append("其他" + "(" + uploadBean.getOtherSymptoms()
						+ ")");
			}
		}
		setText(R.id.glycuresis_edt_weight, uploadBean.getWeight());
		String xueya1 = TextUtils.isEmpty(uploadBean.getDiastolic()) ? ""
				: uploadBean.getDiastolic();
		String xueya2 = TextUtils.isEmpty(uploadBean.getConstriction()) ? ""
				: uploadBean.getConstriction();
		setText(R.id.glycuresis_edt_bloodpresure, xueya2 + "/" + xueya1);
		setText(R.id.glycuresis_edt_index, uploadBean.getBmi());
		setText(R.id.glycuresis_symps, sb_symptoms.toString());

		setText(R.id.glycuresis_edt_weighttarget, uploadBean.getTargetWeight());

		setText(R.id.glycuresis_edt_signother, uploadBean.getOtherSigns());
		String zubei = uploadBean.getPulsation();
		if ("2".equals(zubei)) {
			setText(R.id.glycuresis_edt_zubei, "触及");
		} else if ("1".equals(zubei)) {
			setText(R.id.glycuresis_edt_zubei, "未触及");
		}

		setText(R.id.glycuresis_edt_smoking, uploadBean.getSmokeCount());
		setText(R.id.glycuresis_edt_smokingtarget,
				uploadBean.getTargetSmokeCount());
		String yinjiu = uploadBean.getDrinkTypeCode();
		// 饮酒类型
		String[] yinjius = yinjiu.split(",");
		StringBuilder sb_yinjiu = new StringBuilder();
		for (int j = 0; j < yinjius.length; j++) {
			switch (yinjius[j]) {
			case "1":
				sb_yinjiu.append("白酒(≥42度)\t");
				break;
			case "2":
				sb_yinjiu.append("白酒(＜42度)\t");
				break;
			case "3":
				sb_yinjiu.append("啤酒\t");
				break;
			case "4":
				sb_yinjiu.append("黄酒、米酒\t");
				break;
			case "5":
				sb_yinjiu.append("葡萄酒\t");
				break;
			case "9":
				sb_yinjiu.append("其他\t");
				break;
			case "10":
				sb_yinjiu.append("不饮酒\t");
				break;
			default:
				break;
			}
		}
		setText(R.id.glycuresis_edt_drinkingtype, sb_yinjiu.toString());
		setText(R.id.glycuresis_edt_drinking, uploadBean.getDrinkCount());
		setText(R.id.glycuresis_edt_drinkingtarget,
				uploadBean.getTargetDrinkCount());
		setText(R.id.glycuresis_edt_sport1, uploadBean.getTrainTimesWeek());
		setText(R.id.glycuresis_edt_sport1target,
				uploadBean.getTargetTrainTimesWeek());
		setText(R.id.glycuresis_edt_sport2, uploadBean.getTrainMinute());
		setText(R.id.glycuresis_edt_sport2target,
				uploadBean.getTargetTrainMinute());
		// 需要减重
		String loseWeight = uploadBean.getLoseWeight();
		if (loseWeight.equals("1")) {
			loseWeight = "不需要";
		} else if (loseWeight.equals("2")) {
			loseWeight = "需要";
		}
		setText(R.id.glycuresis_et_needjianqingweight, loseWeight);
		setText(R.id.glycuresis_et_food, uploadBean.getFood());
		setText(R.id.edt_foodtarget, uploadBean.getTargetFood());
		setText(R.id.glycuresis_edt_sugar, uploadBean.getFbs());
		setText(R.id.glycuresis_edt_sugarcanhou, uploadBean.getPbs());
		// 心理咨询
		String xinli = uploadBean.getPsychologyChange();
		switch (xinli) {
		case "1":
			xinli = "良好";
			break;
		case "2":
			xinli = "一般";
			break;
		case "3":
			xinli = "差";
			break;
		default:
			break;
		}
		setText(R.id.glycuresis_sce_mentaladjust, xinli);
		// 遵医
		String zhunyi = uploadBean.getObeyDoctor();
		switch (zhunyi) {
		case "1":
			zhunyi = "良好";
			break;
		case "2":
			zhunyi = "一般";
			break;
		case "3":
			zhunyi = "差";
			break;
		default:
			break;
		}
		setText(R.id.glycuresis_sce_obey, zhunyi);
		setText(R.id.glycuresis_edt_TC, uploadBean.getTc());
		setText(R.id.glycuresis_edt_HDL, uploadBean.getHdl());
		setText(R.id.glycuresis_et_LDL, uploadBean.getLdl());
		setText(R.id.glycuresis_edt_hemoglobin, uploadBean.getHbA1c());
		setText(R.id.glycuresis_edt_examinedate, uploadBean.getTestDate());
		// 服药
		String fuyao = uploadBean.getMedicine();
		switch (fuyao) {
		case "1":
			fuyao = "规律";
			break;
		case "2":
			fuyao = "间断";
			break;
		case "3":
			fuyao = "不服药";
			break;
		case "4":
			fuyao = "拒绝服药";
			break;
		default:
			break;
		}
		setText(R.id.glycuresis_sce_medicalobey, fuyao);

		// 药物不良反应
		String ywblfy = uploadBean.getAdverseReactions();
		switch (ywblfy) {
		case "1":
			ywblfy = "无";
			break;
		case "2":
			ywblfy = "有";
			break;
		default:
			break;
		}
		setText(R.id.glycuresis_scedt_drugreaction, ywblfy);
		// 低血糖反应
		String dxtfy = uploadBean.getGlycopenia();
		switch (dxtfy) {
		case "1":
			dxtfy = "无";
			break;
		case "2":
			dxtfy = "偶尔";
			break;
		case "3":
			dxtfy = "频繁";
			break;
		default:
			break;
		}
		setText(R.id.glycuresis_sce_rhg, dxtfy);
		// 随访分类
		String sffl = uploadBean.getVisitType();
		switch (sffl) {
		case "1":
			sffl = "控制满意";
			break;
		case "2":
			sffl = "控制不满意";
			break;
		case "3":
			sffl = "不良反应";
			break;
		case "4":
			sffl = "并发症";
			break;
		default:
			break;
		}
		setText(R.id.glycuresis_sce_tureclass, sffl);

		setText(R.id.glycuresis_referral_Organization,
				uploadBean.getReferralOffice());
		// 并发症变化
		String bfzbh = uploadBean.getComplicationChange();
		switch (bfzbh) {
		case "1":
			bfzbh = "有新并发症";
			break;
		case "2":
			bfzbh = "原有并发症加重";
			break;
		default:
			break;
		}
		setText(R.id.glycuresis_edt_bingfazheng, bfzbh);
		setText(R.id.glycuresis_referral_reason, uploadBean.getReferralReason());
		String xml = uploadBean.getXml();
		List<MedicineDesc> lists = XmlTool.parseMedicineDescByxml(xml);
		if (lists != null && lists.size() > 0) {
			int index = 0;
			MedicineDesc bean = null;
			for (int i = 0; i < lists.size(); i++) {
				bean = lists.get(i);
				if (index == 0) {
					otherMedicineDesc1_et.setText(bean.getOtherMedicineDesc());
					medicineFrequency1_et.setText(bean.getMedicineFrequency());
					medicineDosage1_et.setText(bean.getMedicineDosage());
					index = 1;
					continue;
				}
				if (index == 1) {
					otherMedicineDesc2_et.setText(bean.getOtherMedicineDesc());
					medicineFrequency2_et.setText(bean.getMedicineFrequency());
					medicineDosage2_et.setText(bean.getMedicineDosage());
					index = 2;
					continue;
				}
				if (index == 2) {
					otherMedicineDesc3_et.setText(bean.getOtherMedicineDesc());
					medicineFrequency3_et.setText(bean.getMedicineFrequency());
					medicineDosage3_et.setText(bean.getMedicineDosage());
					index = 3;
					continue;
				}
				if (index == 3) {
					otherMedicineDesc4_et.setText(bean.getOtherMedicineDesc());
					medicineFrequency4_et.setText(bean.getMedicineFrequency());
					medicineDosage4_et.setText(bean.getMedicineDosage());
				}
			}
		}
	}

	/***
	 * 保存到数据库
	 */

	private void setChoiceEditText() {
		setChoiceEditText(R.id.glycuresis_edt_drinkingtype, new String[] {
				"白酒(≥42度)", "白酒(＜42度)", "啤酒", "黄酒、米酒", "葡萄酒", "其他", "不饮酒" },
				null);
		setChoiceEditText(R.id.glycuresis_sce_tureclass, new String[] { "控制满意",
				"控制不满意", "不良反应", "并发症" }, null);
		setChoiceEditText(R.id.glycuresis_edt_bingfazheng, new String[] {
				"有新并发症", "原有并发症加重" }, null);
		setChoiceEditText(R.id.glycuresis_sce_mentaladjust, new String[] {
				"良好", "一般", "差", }, null);
		setChoiceEditText(R.id.glycuresis_et_needjianqingweight, new String[] {
				"需要", "不需要", }, null);
		setChoiceEditText(R.id.glycuresis_sce_obey, new String[] { "良好", "一般",
				"差", }, null);
		setChoiceEditText(R.id.glycuresis_scedt_drugreaction, new String[] {
				"无", "有" }, null);
		setChoiceEditText(R.id.glycuresis_edt_zubei,
				new String[] { "未触及", "触及" }, null);
		setChoiceEditText(
				R.id.glycuresis_symps,
				getResources().getStringArray(R.array.select_glycuresissymptom),
				"其他");
		setChoiceEditText(R.id.glycuresis_turemethod, new String[] { "门诊",
				"家庭", "电话", "短信", "网络", "其他" }, null);
		setChoiceEditText(R.id.glycuresis_sce_medicalobey, new String[] { "规律",
				"间断", "不服药" }, null);
		setChoiceEditText(R.id.glycuresis_sce_rhg, new String[] { "无", "偶尔",
				"频繁" }, null);
		setChoiceEditText(R.id.hypertension_zhuangui, new String[] { "继续随访",
				"暂时失访", "终止管理" }, null);
	}
}
